import 'dart:async';
import 'dart:io';

import 'package:ch_router/ch_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lmreader/pages/splash/splash_cache_manager.dart';
import 'package:video_player/video_player.dart';

import '../../common/index.dart';

class SplashPage extends ConsumerStatefulWidget {
  const SplashPage({super.key, this.playCompleted});
  final Function()? playCompleted;

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _SplashPageState();
}

class _SplashPageState extends ConsumerState<SplashPage> {
  var count = 5;
  late Countdown _countdown;
  bool _isInitialized = false;
  late VideoPlayerController _controller;
  late File splashFile;
  bool isVideo = false;

  @override
  void initState() {
    super.initState();

    if (isVideo) {
      _initVideo();
    } else {
      _initImage();
    }
  }

  _initImage() async {
    final file = await SplashCacheManager().getImage(
        'https://picx.zhimg.com/v2-3d9926290f980db99e56057aee494883_b.jpg');
    setState(() {
      splashFile = file;
      _isInitialized = true;
    });
    _doCountDown();
  }

  _initVideo() async {
    final file = await SplashCacheManager().getVideo(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4');
    splashFile = file;
    _controller = VideoPlayerController.file(file)
      ..addListener(() {
        setState(() {});
      })
      ..initialize().then((_) {
        setState(() {
          _isInitialized = true;
        });
        _controller.play();
        _doCountDown();
      });
  }

  @override
  void dispose() {
    print("释放");
    _countdown.clear();
    try {
      _controller.dispose();
    } catch (e) {
      print("变量尚未初始化");
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildView(),
    );
  }

  /// 主视图
  Widget _buildView() {
    return _isInitialized
        ? (isVideo ? _buildVideo() : _buildPicture(splashFile))
        : const CircularProgressIndicator();
  }

  /// Video
  Widget _buildVideo() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.lightBlue,
      child: AspectRatio(
        aspectRatio: _controller.value.aspectRatio,
        child: VideoPlayer(_controller),
      ),
    );
  }

  /// Picture
  Widget _buildPicture(File file) {
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: Image(
        image: FileImage(file),
        fit: BoxFit.fill,
      ),
    );
  }

  void _doCountDown() {
    _countdown = Countdown(5, (second) {
      if (second > 0) {
        setState(() {
          count = second;
        });
      } else {
        if (widget.playCompleted != null) {
          widget.playCompleted!();
        } else {
          if (CHNavigator.canPop()) {
            CHNavigator.pop();
          } else {
            CHNavigator.pushReplacement(RouteNames.home);
          }
        }
      }
    });
    _countdown.start();
  }
}

class Countdown {
  int _secondsRemaining;
  Timer? _timer;
  final Function(int second)? onCallback;

  Countdown(this._secondsRemaining, this.onCallback);

  void start() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_secondsRemaining > 0) {
        _secondsRemaining--;
        onCallback!(_secondsRemaining);
      } else {
        _timer?.cancel();
        onCallback!(0);
      }
    });
  }

  void clear() {
    cancel();
    _timer = null;
  }

  void cancel() {
    _timer?.cancel();
  }

  int get secondsRemaining => _secondsRemaining;
}
